<template>
  <v-md-editor
    :height="`${height}px`"
    v-model="content"
    @save="save"
    :disabled-menus="[]"
    @upload-image="pasteImage"
    @change="change"
  ></v-md-editor>
  <el-dialog v-model="dialogVisible" title="保存" width="30%">
    <el-input v-model="title" placeholder="请输入标题"></el-input>
    <br />
    <br />
    <el-select v-model="type" placeholder="文集">
      <el-option
        v-for="item in options"
        :key="item.id"
        :label="item.name"
        :value="item.id"
      ></el-option>
    </el-select>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, onUnmounted, ref, watch } from "vue";
import {
  ElButton,
  ElMessage,
  ElDialog,
  ElInput,
  ElSelect,
  ElOption,
} from "element-plus";
import "element-plus/es/components/button/style/css";
import "element-plus/es/components/dialog/style/css";
import "element-plus/es/components/message/style/css";
import "element-plus/es/components/input/style/css";
import "element-plus/es/components/select/style/css";
import "element-plus/es/components/option/style/css";
import {
  UploadArticle,
  GetArticleById,
  Upload,
  GetArticleType,
} from "@/api/request";
import router from "@/router";
import { baseURL } from "@/api/axios";
import { useRouter } from "vue-router";
import store from "@/store";

const content = ref("");
const title = ref("");
const type = ref(0);
const describe = ref("");
const dialogVisible = ref(false);
// 记录原始文章数据，用于比较是否有修改
const oldData = ref("");
const height = ref(document.body.clientHeight - 60);
const options = ref([
  {
    id: 0,
    name: "未分类",
  },
]);

watch(
  () => store.state.saveStatus,
  (val) => {
    if (!val) {
      document.title = "* " + document.title;
    }
  }
);

GetArticleType().then((res) => {
  if (res.success) {
    options.value = [...options.value, ...res.data];
  } else {
    ElMessage.error(res.msg);
  }
});

const change = () => {
  if (oldData.value === content.value) {
    store.commit("saveStatus", true);
  } else {
    store.commit("saveStatus", false);
  }
};

if (router.currentRoute.value.params.id[0]) {
  const id = router.currentRoute.value.params.id[0];
  GetArticleById(id).then((res) => {
    if (res.success) {
      content.value = res.data.content;
      title.value = res.data.title;
      type.value = res.data.typeId;
      oldData.value = res.data.content;
    } else {
      ElMessage.error(res.msg);
      router.push("/");
    }
  });
}

/**
 * 检测文章中存在的图片,并上传到服务器
 * @param {string} text 文章内容
 * @returns {string[]} 图片路径数组
 */
const getImagePath = (text) => {
  // 匹配md文件的img标签
  const imgReg = /!\[.*?\]\((.*?)\)/g;
  // 匹配图片中的链接地址
  const imgSrcReg = /\((.*?)\)/;
  // 提取文章中的图片
  const imgArr = [];
  let result;
  while ((result = imgReg.exec(text)) != null) {
    var path = imgSrcReg.exec(result[0])[0];
    path = path.substring(1, path.length - 1);
    imgArr.push(path);
  }
  return imgArr;
};

const save = (text, html) => {
  if (text.trim() === "") {
    ElMessage.error("内容不能为空");
    return;
  }

  // 过滤html中的标签和pre标签中的内容
  const reg = /<\/?[^>]+>/g;
  const regPre = /<pre[^>]*>([\s\S]*?)<\/pre>/g;
  const htmlStr = html.replace(regPre, "").replace(reg, "");
  let str = JSON.stringify(htmlStr)
    .replace(/\s+/g, " ")
    .replaceAll("\\n", "")
    .replaceAll("\\t", "")
    .replace(/^"|"$/g, "");
  describe.value = str.length > 200 ? str.substring(0, 200) + "..." : str;
  // 取出html中的第一个h1标签
  const regH1 = /<h1[^>]*>([\s\S]*?)<\/h1>/g;
  const h1 = regH1.exec(html);
  if (!router.currentRoute.value.params.id[0] && h1) {
    title.value = h1[1];
  }
  let imgs = getImagePath(text);
  console.log(imgs);
  if (imgs.length != 0) {
    ElMessage.warning(
      `检测到文章中存在${imgs.length}图片，正在上传图片，请稍后`
    );
    // imgs.forEach(item=>{
    //     if(item.)

    // })
  }
  dialogVisible.value = true;
};
const submit = () => {
  if (title.value.trim() === "") {
    ElMessage.error("标题不能为空");
    return;
  }
  // 标题不能超过100个字符
  if (title.value.length > 100) {
    ElMessage.error("标题不能超过100个字符");
    return;
  }

  UploadArticle({
    id: router.currentRoute.value.params.id[0] || 0,
    title: title.value,
    content: content.value,
    describe: describe.value,
    typeId: type.value,
  }).then((res) => {
    if (res.success) {
      ElMessage.success("保存成功");
      dialogVisible.value = false;
      store.commit("saveStatus", true);
      router.push("/");
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const pasteImage = (event, insertImage, files) => {
  // 读取剪贴板图片
  Upload({ type: "img", file: files[0] }).then((res) => {
    if (res.success) {
      ElMessage.success("上传成功");
      insertImage({
        url: window.baseUrl + "/upload/" + res.data.path,
        desc: new Date().getTime(),
      });
    } else {
      ElMessage.error(res.msg);
    }
  });
};

window.onresize = () => {
  height.value = document.body.clientHeight - 60;
};
</script>
